package com.lib.framework.helper

import android.util.Log

/**
 * Copyright (C), 2018-2019, 享物说
 * FileName: CalcTimeDuringHelper
 * Author: keanbin
 * Date: 2019-11-22 11:35
 * Description: 计算时间段监听器
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class CalcTimeDuringHelper {

    companion object {
        private const val TAG = "CalcTimeDuringHelper"

        /**
         * 全局的实例
         */
        @JvmField
        val sGlobalCalcTimeDuringHelper = CalcTimeDuringHelper()
    }

    /**
     * 开始时间
     */
    private var mStartTime = 0L

    /**
     * 开始，设置当前时间为 开始时间
     */
    fun start(msg: String = "") {
        if (msg.isNotEmpty()) {
            Log.i(TAG, "start msg = $msg")
        }

        mStartTime = System.currentTimeMillis()
    }

    /**
     * 输出 开始时间到当前时间的 时间段信息
     *
     * @param msg 先打印的信息
     * @param isResetStartTime 输出完之后是否重置 开始时间 为当前事件
     */
    fun endTimeDuring(msg: String = "", isResetStartTime: Boolean = false) {
        if (msg.isNotEmpty()) {
            Log.i(TAG, "endTimeDuring msg = $msg")
        }

        if (mStartTime <= 0) {
            Log.i(TAG, "endTimeDuring error : mStartTime = $mStartTime")
            return
        }

        val now = System.currentTimeMillis()
        val during = now - mStartTime
        val duringText = getDuringText(during)
        Log.i(TAG, "endTimeDuring during : duringText = $duringText, mStartTime = $mStartTime, now = $now, during = $during")

        if (isResetStartTime) {
            mStartTime = now
        }
    }

    /**
     * 获取时间段文本
     */
    private fun getDuringText(during: Long): String {
        var minute = 0L
        var second = during / 1000
        if (second > 60) {
            minute = second / 60
            second %= 60
        }

        var text = ""
        if (minute > 0) {
            text += "$minute 分 "
        }

        text += "$second 秒"

        return text
    }
}